package rush.rushcampus.service.impl;

import org.springframework.beans.BeanUtils;
import rush.rushcampus.common.BaseContext;
import rush.rushcampus.dto.ArticleTagDto;
import rush.rushcampus.entity.ArticleTag;
import rush.rushcampus.mapper.ArticleTagMapper;
import rush.rushcampus.service.IArticleTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author rush
 * @since 2024-06-11
 */
@Service
public class ArticleTagServiceImpl extends ServiceImpl<ArticleTagMapper, ArticleTag> implements IArticleTagService {

    @Override
    public void addArticleTag(ArticleTagDto articleTagDto) {
        ArticleTag articleTag = new ArticleTag();
        BeanUtils.copyProperties(articleTagDto, articleTag);
        //不做处理，直接插入
        //随机生成一个标签颜色（rgb）
        articleTag.setCreateTime(LocalDateTime.now());
        articleTag.setColor(randomColor());
        articleTag.setViews(0L);
        articleTag.setStar(0L);
        articleTag.setArticleCount(0);
        articleTag.setUserId(BaseContext.getCurrenId());
        articleTag.setStatus(1);
        baseMapper.insert(articleTag);
    }

    @Override
    public ArticleTag getTag(Long id) {
        //将view自增加一
        ArticleTag articleTag = baseMapper.selectById(id);
        articleTag.setViews(articleTag.getViews() + 1);
        return articleTag;
    }

    private String randomColor() {
        // 创建一个随机生成器
        Random rand = new Random();

        // 随机生成一个0到16777215之间的整数
        int colorInt = rand.nextInt(16777216);

        // 将整数转换为16进制字符串
        String colorCode = String.format("#%06x", colorInt);
        return colorCode;
    }
}
